import React, {useEffect, useState} from "react";
import UploadObjModal from "@/components/UploadObjModal.tsx";
import {Button, Image, Input, Popconfirm, Select, Table} from "antd";
import objApi from "@/api/ObjApi.ts";
import ObjApi from "@/api/ObjApi.ts";
import {IPage, ObjInfo, ObjType} from "@/api/Types/ObjInterfaces.ts";
import UserInfoViewer from "@/components/UserInfoViewer.tsx";

const AdminObjectPage: React.FC = () => {
    const [uploadObjModalOpen, setUploadObjModal] = useState(false)
    const [objInfoPage, setObjInfoPage] = useState<IPage<ObjInfo>>(null)
    const [triggerLoad, setTriggerLoad] = useState(0)
    const [userInfoViewer, setUserInfoViewer] = useState<UserInfoViewer>()
    const [imgViewVisible, setImgViewVisible] = useState(false)
    const [imgLink, setImgLink] = useState()

    const [objTypes, setObjTypes] = useState<Map<string, ObjType>>(null)

    const refresh = () => {
        setTriggerLoad(triggerLoad + 1);
    }

    useEffect(() => {
        objApi.pageAllObj(1, 10).then((data) => {
            UserInfoViewer.init(data.records.map(item => item.createUser)).then((uiv) => {
                setObjInfoPage(data)
                setUserInfoViewer(uiv)
            })
        })
        ObjApi.getObjTypes().then((data) => {
            const map = new Map<string, ObjType>()
            data.forEach(item => {
                map.set(item.id, item)
            })
            setObjTypes(map)
        })
    }, [triggerLoad]);

    const onUploadModalClose = (flag: boolean) => {
        setUploadObjModal(flag)
        refresh()
    }

    if (objInfoPage == null || objInfoPage.records == null || objTypes == null) {
        return (
            <Table/>
        )
    }

    return (
        <div>
            <Button
                onClick={() => {
                    setUploadObjModal(true)
                }}
            >上传文件</Button>
            <Image
                width={200}
                style={{display: 'none'}}
                preview={{
                    visible: imgViewVisible,
                    src: "api/obj/" + imgLink,
                    onVisibleChange: (v) => {
                        setImgViewVisible(v);
                    },
                }}
            />
            <Table
                dataSource={objInfoPage.records}
                rowKey="id"
                pagination={{
                    current: objInfoPage.current,
                    pageSize: objInfoPage.size,
                    total: objInfoPage.total,
                    onChange: (page, pageSize) => {
                        objApi.pageAllObj(page, pageSize).then(data => {
                            setObjInfoPage(data)
                        })
                    },
                    showSizeChanger: true,
                }}
            >
                <Table.Column
                    title="id"
                    dataIndex="id"
                    key="id"
                />
                <Table.Column
                    title="名称"
                    dataIndex="objName"
                    key="objName"
                    render={(value: string, record: ObjInfo, index) => {
                        const split = value.split('.');
                        return (
                            <Input
                                defaultValue={split[0]}
                                variant="filled"
                                onBlur={(evt) => {
                                    const newVal = evt.target.value + '.' + split[1];
                                    if (newVal == value) {
                                        return
                                    }
                                    ObjApi.changeObjName(record.id, newVal)
                                        .then((res) => {
                                            window.messageApi.success("更新成功")
                                        })
                                }}
                            />
                        )
                    }}
                />
                <Table.Column
                    title="类型"
                    dataIndex="objType"
                    key="objType"
                    render={(value: ObjType, record: ObjInfo, index) => {
                        return (
                            <Select
                                onChange={(_v) => {
                                    ObjApi.changeObjType(record.id, _v).then(() => {
                                        refresh()
                                    })
                                }}
                                options={(() => {
                                    const res = []
                                    objTypes.forEach((v, k) => {
                                        res.push({
                                            value: v.id,
                                            label: v.contentName
                                        })
                                    })
                                    return res
                                })()}
                                defaultValue={value.id}
                                style={{minWidth: '100px'}}
                            />
                        )
                    }}
                />
                <Table.Column
                    title="链接"
                    dataIndex="objLink"
                    key="objLink"
                    render={(value, record: ObjInfo, index) => {
                        const contentType = record.objType.contentType;
                        const color = record.objType.color;
                        let onClick = () => {
                            window.messageApi.info(record.objLink).then()
                        }

                        if (contentType.startsWith("image")) {
                            onClick = () => {
                                setImgViewVisible(true)
                                setImgLink(value)
                            }
                        }
                        return (
                            <Button
                                onClick={onClick}
                                type="link"
                                style={{color: color}}
                            >{record.objLink}</Button>
                        )
                    }}
                />
                <Table.Column
                    title="创建时间"
                    dataIndex="createTime"
                    key="createTime"
                />
                <Table.Column
                    title="创建用户"
                    dataIndex="createUser"
                    key="createUser"
                    render={(value, record, index) => {
                        return (
                            <Button type='text'
                                    onClick={() => {
                                        userInfoViewer.show(value)
                                    }}
                            >
                                {userInfoViewer.getNickNameById(value)}
                            </Button>
                        )
                    }}
                />
                <Table.Column
                    title="操作"
                    dataIndex="id"
                    key="id"
                    render={(value, record, index) => {
                        if (value == null) {
                            return null
                        }
                        return (
                            <Popconfirm title="确定删除？"
                                        onConfirm={() => {
                                            ObjApi.deleteObj(value).then(() => {
                                                window.messageApi.info("删除成功").then()
                                                refresh()
                                            })
                                        }}
                            >
                                <Button type='text'>
                                    删除
                                </Button>
                            </Popconfirm>
                        )
                    }}
                />
            </Table>
            <UploadObjModal open={uploadObjModalOpen} setOpen={onUploadModalClose}/>
        </div>
    )
}
export default AdminObjectPage